local blaze = require "blaze"
local app = require "app"

local game = app.game.running
local i18n_number = app.i18n.number

local M = game.ui.element()

local log = game.logging.get("RoomItem")

local function get_limitation_text(min, max)
    local prefix = app.i18n.text("room:limit")
    if min <= 0 and max <= 0 then
        return string.format("%s%s", prefix, app.i18n.text("room:unlimited"))
    end
    if min <= 0 then
        max = i18n_number(max, "chip3")
        return string.format("%s0 - %s", prefix, max)
    end
    if max <= 0 then
        min = i18n_number(min, "chip3")
        return string.format("%s%s - %s", prefix, min, app.i18n.text("room:infinity"))
    end
    min = i18n_number(min, "chip3")
    max = i18n_number(max, "chip3")
    return string.format("%s%s - %s", prefix, min, max)
end

local function check(self)
    local chip = app.kbe.player().chip
    local min = self.room.chip_limit_min
    local max = self.room.chip_limit_max

    if chip >= min then
        if max <= 0 or chip <= max then
            return true
        end
    end

    local reason = ""
    if chip < min then
        reason = app.i18n.text("room:too little chips")
        log.debug(string.format("%d < %d", chip, min))
    elseif chip > max then
        reason = app.i18n.text("room:too much chips")
        log.debug(string.format("%d > %d", chip, max))
    end

    return false, reason
end

local function enter_fail_tip(reason)
    app.msgbox.show(
        {
            content = reason,
        }
    )
end

local function do_enter(config_id)
    return game.kbe.player().room_api
        :enter_by_config(config_id)
        :next(function() game.game_scene.enter(config_id) end)
end

function M:ctor(data)
    self.room = data
end

function M:on_injected(bind)
    bind("button.click", self.button, self.on_click)
    app.utility.button_style.highlight_scale(self.button)

    local room = self.room
    self.chip_txt.text = get_limitation_text(room.chip_limit_min, room.chip_limit_max)
end

function M:on_click()
    if game.reconnection.resume() then
        return
    end

    local ok, reason = check(self)
    if ok then
        do_enter(self.room.config_id)
        return
    end
    
    local recommended = app.store.rooms.state.recommended
    if recommended then
        -- 有可推荐的房间，询问是否直接进入
        app.msgbox.show({
            content = app.i18n.text("room:recommended", { reason = reason }),
            cancelable = true,
            on_confirm = function() do_enter(recommended.config_id) end
        })
        return
    end

    -- 没有可推荐的房间，直接显示无法进入弹窗
    app.msgbox.show({
        content = reason,
        cancelable = false
    })
end

return M